package com.cosmoplat.xikai.business.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cosmoplat.xikai.business.domain.BaseAlarmRecord;
import com.cosmoplat.xikai.business.domain.DeviceLog;
import com.cosmoplat.xikai.business.domain.DeviceProductLog;
import com.cosmoplat.xikai.business.service.BaseAlarmRecordService;
import com.cosmoplat.xikai.business.service.DeviceLogService;
import com.cosmoplat.xikai.business.service.DeviceProductLogService;
import com.cosmoplat.xikai.common.utils.StringUtils;
import com.cosmoplat.xikai.common.utils.uuid.UUID;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName RemoveHistoryLogTask
 * @Description 删除历史任务
 * @Author wdf
 * @Date 2025/1/22
 */
@Slf4j
@Component("removeHistory")
public class RemoveHistoryLogTask {

    @Value("${removeHistory.keepDays:180}")
    private Integer removeHistoryKeepDays;

    /**
     * 删除日志的批次大小 单次任务执行的时候最多执行多少次删除操作
     */
    @Value("${removeHistory.removeHistoryLogBatchSize:10000}")
    private Integer removeHistoryLogBatchSize;

    /**
     * 删除日志的批次大小 单次删除的条数限制
     */
    @Value("${removeHistory.removeHistoryLogBatchLimitSize:200}")
    private Integer removeHistoryLogBatchLimitSize;



    @Autowired
    private DeviceProductLogService deviceProductLogService;

    @Autowired
    private DeviceProductLogService productLogService;

    @Autowired
    private BaseAlarmRecordService alarmRecordService;

    @Autowired
    private DeviceLogService deviceLogService;


    /**
     * 删除device_log
     */
    public void removeDeviceLog(Integer keepDays) {
        String uuid = UUID.randomUUID().toString();
        log.info(uuid + "启动删除接口日志...");
        log.info(uuid + "任务传入参数, 保留天数：{}", keepDays);
        if (keepDays == null) {
            keepDays = removeHistoryKeepDays;
        }

        log.info(uuid + "删除表：{}, 保留的日志天数 {}", keepDays);
        log.info(uuid + "删除的总批次：{}, 单次删除的数量：{}", removeHistoryLogBatchSize, removeHistoryLogBatchLimitSize);
        try {
            // 删除时间
            LocalDateTime localDateTime = LocalDateTime.now().minus(keepDays, ChronoUnit.DAYS);
            // 将 LocalDateTime 转换为 Date
            Date localDate = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
            log.info(uuid + "删除时间：{}", localDateTime);
            int i = removeHistoryLogBatchSize;
            while (i > 0) {
                QueryWrapper<DeviceLog> wrapper = new QueryWrapper<>();
                wrapper.select(" top  " + removeHistoryLogBatchLimitSize + " id ", " data_time ")
                        .orderByAsc("id");
                List<DeviceLog> list = deviceLogService.list(wrapper);
                if (CollectionUtils.isEmpty(list)) {
                    break;
                }
                List<Long> ids = list.stream().filter(x -> x.getDataTime().before(localDate)).map(DeviceLog::getId).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(ids)) {
                    break;
                }
                deviceLogService.removeByIds(ids);
                i--;
            }
            log.info(uuid + "{} 删除的剩余次数：{}", removeHistoryLogBatchSize, i);
        } catch (Exception e) {
            log.error("删除接口日志出现异常：{}", e);
        }
        log.info(uuid + "删除接口日志完成");
    }

    /**
     * 删除产品日志
     */
    public void removeProductLog(Integer keepDays) {
        String uuid = UUID.randomUUID().toString();
        log.info(uuid + "启动删除接口日志...");
        log.info(uuid + "任务传入参数, 保留天数：{}", keepDays);
        if (keepDays == null) {
            keepDays = removeHistoryKeepDays;
        }

        log.info(uuid + "删除表：{}, 保留的日志天数 {}", keepDays);
        log.info(uuid + "删除的总批次：{}, 单次删除的数量：{}", removeHistoryLogBatchSize, removeHistoryLogBatchLimitSize);
        try {
            // 删除时间
            LocalDateTime localDateTime = LocalDateTime.now().minus(keepDays, ChronoUnit.DAYS);
            // 将 LocalDateTime 转换为 Date
            Date localDate = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
            log.info(uuid + "删除时间：{}", localDateTime);
            int i = removeHistoryLogBatchSize;
            while (i > 0) {
                QueryWrapper<DeviceProductLog> wrapper = new QueryWrapper<>();
                wrapper.select(" top  " + removeHistoryLogBatchLimitSize + " id ",  " create_time ")
                        .orderByAsc("id");
                List<DeviceProductLog> list = productLogService.list(wrapper);
                if (CollectionUtils.isEmpty(list)) {
                    break;
                }
                List<Long> ids = list.stream().filter(x -> x.getCreateTime().before(localDate)).map(DeviceProductLog::getId).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(ids)) {
                    break;
                }
                productLogService.removeByIds(ids);
                i--;
            }
            log.info(uuid + "{} 删除的剩余次数：{}", removeHistoryLogBatchSize, i);
        } catch (Exception e) {
            log.error("删除接口日志出现异常：{}", e);
        }
        log.info(uuid + "删除接口日志完成");
    }

    /**
     * 删除报警记录
     */
    public void removeAlarmRecord(Integer keepDays) {
        String uuid = UUID.randomUUID().toString();
        log.info(uuid + "启动删除接口日志...");
        log.info(uuid + "任务传入参数, 保留天数：{}", keepDays);
        if (keepDays == null) {
            keepDays = removeHistoryKeepDays;
        }

        log.info(uuid + "删除表：{}, 保留的日志天数 {}", keepDays);
        log.info(uuid + "删除的总批次：{}, 单次删除的数量：{}", removeHistoryLogBatchSize, removeHistoryLogBatchLimitSize);
        try {
            // 删除时间
            LocalDateTime localDateTime = LocalDateTime.now().minus(keepDays, ChronoUnit.DAYS);
            // 将 LocalDateTime 转换为 Date
            Date localDate = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
            log.info(uuid + "删除时间：{}", localDateTime);
            int i = removeHistoryLogBatchSize;
            while (i > 0) {
                QueryWrapper<BaseAlarmRecord> wrapper = new QueryWrapper<>();
                wrapper.select(" top  " + removeHistoryLogBatchLimitSize + " id ", "alarm_start_time")
                        .orderByAsc("id");
                List<BaseAlarmRecord> list = alarmRecordService.list(wrapper);
                if (CollectionUtils.isEmpty(list)) {
                    break;
                }
                List<Long> ids = list.stream().filter(x -> x.getAlarmStartTime().before(localDate)).map(BaseAlarmRecord::getId).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(ids)) {
                    break;
                }
                productLogService.removeByIds(ids);
                i--;
            }
            log.info(uuid + "{} 删除的剩余次数：{}", removeHistoryLogBatchSize, i);
        } catch (Exception e) {
            log.error("删除接口日志出现异常：{}", e);
        }
        log.info(uuid + "删除接口日志完成");
    }


}
